package com.unistrong.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @program dsadapter-service
 * @description:
 * @author: qipengbo
 * @create: 2021/06/25 11:12
 */

@MapperScan(basePackages = "com.unistrong.mapper", sqlSessionFactoryRef = "pgSqlSessionFactory")
public class PostgreDataSourceConfig {

    @Bean(name = "pgDataSource")
//    @Primary
    @ConfigurationProperties("spring.datasource.druid.ds-postgre")
    public DataSource pgDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "pgSqlSessionFactory")
//    @Primary
    public SqlSessionFactory pgSqlSessionFactory(@Qualifier("pgDataSource") DataSource datasource)
            throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper.postgre/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "pgSqlSessionTemplate")
//    @Primary
    public SqlSessionTemplate oracleSqlSessionTemplate(
            @Qualifier("pgSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}
